﻿using System.Diagnostics;

using ImageProcessing.Comm;
using ImageProcessing.Controllers;
using ImageProcessing.DataCenters;
using ImageProcessing.HttpRequest;
using ImageProcessing.Model.DataCenter;

namespace ImageProcessing.Service
{
    public class ImageProcessingService
    {
        private readonly ILogger<ImageProcessingService> _logger;
        private readonly IHttpRequests _httpRequest;
        private readonly IDataCenter _dataCenter;
        private IConfiguration _configuration;

        public ImageProcessingService(IConfiguration configuration, ILogger<ImageProcessingService> logger, IHttpRequests httpRequest, IDataCenter dataCenter)
        {
            _configuration = configuration;
            _dataCenter = dataCenter;
            _httpRequest = httpRequest;
            _logger = logger;
        }

        public async Task<(string modelPath, string tensorrtPath, string projectPath)> setPathAsync()
        {
            // 获取程序的根目录
            string projectPath = AppDomain.CurrentDomain.BaseDirectory;
            // 设置 TensorRT 环境变量路径
            string tensorrtPath = Path.Combine(projectPath, @"windows-x64\imagedr-windows-x64-sdk-v1.2\windows-x64");
            string currentPath = Environment.GetEnvironmentVariable("PATH") ?? "";
            string newPath = tensorrtPath + ";" + currentPath;
            Environment.SetEnvironmentVariable("PATH", newPath);
            //设置模型文件的相对路径
            string modelPath = Path.Combine(projectPath, @"windows-x64\models");
            return (modelPath, tensorrtPath, projectPath);
        }

        /// <summary>
        /// 图片去黑边
        /// </summary>
        public async Task<string> removeMask(string picUrl, string picMaskUrl)
        {
            try
            {
                //设置环境变量及获取路径
                var path = await setPathAsync();
                string modelPath = path.Item1;
                string projectPath = path.Item3;
                string picName = Guid.NewGuid().ToString();
                string fullPath = Path.Combine(projectPath, @"file\input\" + picName + ".jpg");
                string resultFullPath = Path.Combine(projectPath, @"file\output\" + picName + ".jpg");
                //调用图片
                var stream = await _httpRequest.GetDataCenterFileAsync(picUrl);
                if (stream == null)
                {
                    return "无法获取该图片";
                }
                ImageSaver.SaveImageFromStream(stream, fullPath);
                try
                {
                    // 使用单例实例
                    CvLibInterop1 interop = CvLibInterop1.Instance;
                    if (interop == null)
                    {
                        return "使用单例实例CvLibInterop1为空";
                    }
                    nint handler = interop.initImageDrHander(modelPath, -1);
                    interop.removeBlackEdges(fullPath, resultFullPath, 100);

                    //上传数据中心
                    var memoryStream = FileToMemoryStreamConverter.ConvertFileToMemoryStream(resultFullPath);
                    var rest = await _dataCenter.UploadAsync(memoryStream);

                    // 清除文件夹内容
                    DeleteFile(Path.GetDirectoryName(fullPath), Path.GetDirectoryName(resultFullPath));

                    var dataCenterUrl = _configuration["service:dcmanager:url-test"] + "/dc/v1/file/downloadByLocal?fileId=";
                    dataCenterUrl += rest.data.fileId;
                    return dataCenterUrl;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 图片去黑边
        /// </summary>
        public async Task<string> removeBlackDdges(string picUrl)
        {
            try
            {
                //设置环境变量及获取路径
                var path = await setPathAsync();
                string modelPath = path.Item1;
                string projectPath = path.Item3;
                string picName = Guid.NewGuid().ToString();
                string fullPath = Path.Combine(projectPath, @"file\input\" + picName + ".jpg");
                string resultFullPath = Path.Combine(projectPath, @"file\output\" + picName + ".jpg");
                //调用图片
                var stream = await _httpRequest.GetDataCenterFileAsync(picUrl);
                if (stream == null)
                {
                    return "无法获取该图片";
                }
                ImageSaver.SaveImageFromStream(stream, fullPath);
                try
                {
                    // 使用单例实例
                    CvLibInterop1 interop = CvLibInterop1.Instance;
                    if (interop == null)
                    {
                        return "使用单例实例CvLibInterop1为空";
                    }
                    nint handler = interop.initImageDrHander(modelPath, -1);
                    interop.removeBlackEdges(fullPath, resultFullPath, 100);

                    //上传数据中心
                    var memoryStream = FileToMemoryStreamConverter.ConvertFileToMemoryStream(resultFullPath);
                    var rest = await _dataCenter.UploadAsync(memoryStream);

                    // 清除文件夹内容
                    DeleteFile(Path.GetDirectoryName(fullPath), Path.GetDirectoryName(resultFullPath));

                    var dataCenterUrl = _configuration["service:dcmanager:url-test"] + "/dc/v1/file/downloadByLocal?fileId=";
                    dataCenterUrl += rest.data.fileId;
                    return dataCenterUrl;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 图片旋转
        /// </summary>
        public async Task<string> PicRotate(string picUrl, int angle)
        {
            try
            {
                //设置环境变量及获取路径
                var path = await setPathAsync();
                string modelPath = path.Item1;
                string projectPath = path.Item3;
                string picName = Guid.NewGuid().ToString();
                string fullPath = Path.Combine(projectPath, @"file\input\" + picName + ".jpg");
                string resultFullPath = Path.Combine(projectPath, @"file\output\" + picName + ".jpg");
                //调用图片
                var stream = await _httpRequest.GetDataCenterFileAsync(picUrl);
                if (stream == null)
                {
                    return "无法获取该图片";
                }
                ImageSaver.SaveImageFromStream(stream, fullPath);
                try
                {
                    // 使用单例实例
                    CvLibInterop1 interop = CvLibInterop1.Instance;
                    if (interop == null)
                    {
                        return "使用单例实例CvLibInterop1为空";
                    }
                    nint handler = interop.initImageDrHander(modelPath, -1);
                    interop.rotate(handler, fullPath, angle, resultFullPath);

                    // 进行其他操作...

                    // 释放资源（如果需要）
                    //interop.closeImageDrHandler(handler);
                    //interop.Dispose();

                    //using (var CvLibInterop = new CvLibInterop(cvlibPath))
                    //{
                    //    // 调用初始化函数，获取 ImageDr 对象指针
                    //    IntPtr imageDrPtr = CvLibInterop.initImageDrHander(modelPath, -1);

                    //    // 检查返回的指针是否为空
                    //    if (imageDrPtr == IntPtr.Zero)
                    //    {
                    //        return "检查返回的指针是否为空";
                    //    }
                    //    CvLibInterop.rotate(imageDrPtr, fullPath, angle, resultFullPath);

                    //    // 释放对象
                    //    CvLibInterop.closeImageDrHandler(imageDrPtr);
                    //}
                    //上传数据中心
                    var memoryStream = FileToMemoryStreamConverter.ConvertFileToMemoryStream(resultFullPath);
                    var rest = await _dataCenter.UploadAsync(memoryStream);

                    // 清除文件夹内容
                    DeleteFile(Path.GetDirectoryName(fullPath), Path.GetDirectoryName(resultFullPath));

                    var dataCenterUrl = _configuration["service:dcmanager:url-test"] + "/dc/v1/file/downloadByLocal?fileId=";
                    dataCenterUrl += rest.data.fileId;
                    return dataCenterUrl;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 调整图像比度和亮度
        /// 亮度brightValue的取值范围：1 -- 100
        /// 对比度contrast的取值范围：100 -- 200
        /// gammaValue的取值范围1.0 -- 20.0 调整的步进可取0.5
        /// </summary>
        public async Task<string> changeContrastAngBright(string picUrl, int brightValue, int contrast, double gammaValue, bool isGammaValue = false)
        {
            try
            {
                //设置环境变量及获取路径
                var path = await setPathAsync();
                string modelPath = path.Item1;
                string projectPath = path.Item3;
                string picName = Guid.NewGuid().ToString();
                string fullPath = Path.Combine(projectPath, @"file\input\" + picName + ".jpg");
                string resultFullPath = Path.Combine(projectPath, @"file\output\" + picName + ".jpg");
                //调用图片
                var stream = await _httpRequest.GetDataCenterFileAsync(picUrl);
                if (stream == null)
                {
                    return "无法获取该图片";
                }
                ImageSaver.SaveImageFromStream(stream, fullPath);
                try
                {
                    // 使用单例实例
                    CvLibInterop1 interop = CvLibInterop1.Instance;
                    if (interop == null)
                    {
                        return "使用单例实例CvLibInterop1为空";
                    }

                    if (isGammaValue)
                    {
                        interop.changeGamma(fullPath, resultFullPath, gammaValue);
                    }
                    else
                    {
                        interop.changeContrastAndBright(fullPath, resultFullPath, contrast, brightValue);
                    }

                    //上传数据中心
                    var memoryStream = FileToMemoryStreamConverter.ConvertFileToMemoryStream(resultFullPath);
                    var rest = await _dataCenter.UploadAsync(memoryStream);

                    // 清除文件夹内容
                    DeleteFile(Path.GetDirectoryName(fullPath), Path.GetDirectoryName(resultFullPath));

                    var dataCenterUrl = _configuration["service:dcmanager:url-test"] + "/dc/v1/file/downloadByLocal?fileId=";
                    dataCenterUrl += rest.data.fileId;
                    return dataCenterUrl;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 删除文件夹中创建时间超过两天的文件
        /// </summary>
        /// <param name="input">要清理的第一个文件夹路径</param>
        /// <param name="output">要清理的第二个文件夹路径</param>
        public void DeleteFile(string input, string output)
        {
            // 获取两天前的时间
            DateTime twoDaysAgo = DateTime.Now.AddDays(-2);

            // 清理第一个文件夹
            DeleteFilesOlderThan(input, twoDaysAgo);

            // 清理第二个文件夹
            DeleteFilesOlderThan(output, twoDaysAgo);
        }

        private void DeleteFilesOlderThan(string directoryPath, DateTime olderThan)
        {
            // 创建DirectoryInfo实例
            DirectoryInfo di = new DirectoryInfo(directoryPath);

            // 检查目录是否存在
            if (!di.Exists)
            {
                Console.WriteLine($"The directory '{directoryPath}' does not exist.");
                return;
            }

            // 获取目录中的所有文件
            FileInfo[] files = di.GetFiles();

            foreach (FileInfo file in files)
            {
                // 检查文件的最后写入时间是否早于两天前
                if (file.LastWriteTime < olderThan)
                {
                    try
                    {
                        // 删除文件
                        file.Delete();
                        Console.WriteLine($"Deleted file: {file.FullName}");
                    }
                    catch (Exception ex)
                    {
                        // 如果删除文件时出现异常，输出错误信息
                        Console.WriteLine($"Error deleting file {file.FullName}: {ex.Message}");
                    }
                }
            }
        }

        /// <summary>
        /// 图片纠斜
        /// </summary>
        public async Task<string> PicDeskewing(string picUrl, int angle)
        {
            try
            {
                //设置环境变量及获取路径
                var path = await setPathAsync();
                string modelPath = path.Item1;
                string projectPath = path.Item3;
                string picName = Guid.NewGuid().ToString();
                string fullPath = Path.Combine(projectPath, @"file\input\" + picName + ".jpg");
                string resultFullPath = Path.Combine(projectPath, @"file\output\" + picName + ".jpg");
                //调用图片
                var stream = await _httpRequest.GetDataCenterFileAsync(picUrl);
                if (stream == null)
                {
                    return "无法获取该图片";
                }
                ImageSaver.SaveImageFromStream(stream, fullPath);
                try
                {
                    // 使用单例实例
                    CvLibInterop1 interop = CvLibInterop1.Instance;
                    if (interop == null)
                    {
                        return "使用单例实例CvLibInterop1为空";
                    }
                    nint handler = interop.initImageDrHander(modelPath, -1);
                    interop.deskewingWithAngle(handler, fullPath, angle, resultFullPath);
                    //上传数据中心
                    var memoryStream = FileToMemoryStreamConverter.ConvertFileToMemoryStream(resultFullPath);
                    var rest = await _dataCenter.UploadAsync(memoryStream);

                    // 清除文件夹内容
                    DeleteFile(Path.GetDirectoryName(fullPath), Path.GetDirectoryName(resultFullPath));

                    var dataCenterUrl = _configuration["service:dcmanager:url-test"] + "/dc/v1/file/downloadByLocal?fileId=";
                    dataCenterUrl += rest.data.fileId;
                    return dataCenterUrl;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 测试
        /// </summary>

        public async Task<string> Inpaint(byte[] image, byte[] mask)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var pic = await _httpRequest.PostAsync<Stream>(_configuration["service:inpaint:url-test"], dic, image, mask);
            //上传数据中心
            var memoryStream = FileToMemoryStreamConverter.ConvertStreamToMemoryStream(pic);
            var rest = await _dataCenter.UploadAsync(memoryStream);

            var dataCenterUrl = _configuration["service:dcmanager:url-test"] + "/dc/v1/file/downloadByLocal?fileId=";
            dataCenterUrl += rest.data.fileId;
            return dataCenterUrl;
        }
    }
}